package demo2;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2023-04-06
 * Time: 6:48
 */


class ListNode {
    int val;
    ListNode next = null;
 }

public class test13 {
    public ListNode reverseKGroup (ListNode head, int k) {
       ListNode tail = head;
       //判断是否有k
        for (int i = 0; i < k; i++) {
            if(tail == null){
                //不足k个的时候,递归结束,返回不足k的链表
                return head;
            }
            tail = tail.next;
        }
        //进行反转---头插法
        ListNode pre = null;//这一个节点相当于每k的第一个节点,
        //head不移动,经过循环,head在最后
        ListNode cur = head;
        while (cur != tail){
            ListNode curNext = cur.next;
            cur.next = pre;
            pre = cur;
            cur = curNext;
        }
        //递开始
        head.next = reverseKGroup(tail,k);
        //归开始
        return pre;
    }
}
